<?php
// +----------------------------------------------------------------------
// | 项目－后台扩展核心类，些类中有登录验证、权限验证、菜单读取……
// +----------------------------------------------------------------------
// | Copyright (c) 2015
// +----------------------------------------------------------------------
// | Author: baiping 125618036@qq.com http://www.webipcode.com
// +----------------------------------------------------------------------
// | 2015-6-25下午6:24:01
// +----------------------------------------------------------------------
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends  CI_Controller{
	
	private $error = '';
	
	public function __construct(){
		parent::__construct();
		error_reporting(E_ALL&~E_NOTICE);//去除Notice错误提示
		$this->load->helper('common');//加载公共函数库
		//判断是否登录
		if( !is_login() ){
			$this->load->helper('url');
			redirect(site_url());
		}
		$this->load->vars('meta_title', '修改配置');
		//加载后点一级菜单
		$this->getFirstMenu();
		
		
		
	}
	
	/**
	 * 是否登录
	 */
	public function isLogin(){
		$user = $this->session->userdata('user_auth');
		if (empty($user)) {
			return 0;
		} else {
			return $this->session->userdata('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
		}
	}
	
	/**
	 * 获取网站配置缓存
	 */
	public function getWebsitCache(){
		$this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));//载入缓存,以文件形式存储
		$website = $this->cache->get('config_data') ;
		return $website;
	}
	
	/**
	 * 弹出框口提示页
	 * @param string $status 状态（success/error）
	 * @param string $msg 提示信息
	 * @param string $tourl 跳转地址
	 */
	public function show_message($status='success', $msg='操作成功', $tourl=''){
		$tourl = empty( $tourl ) ? selfurl() : $tourl;
		$class_name = $status == 'success' ? 'alert-success' : 'alert-danger';
		$msg_arr = array(
				'class_name'=>$class_name,
				'msg_title' => $msg,
				'tourl'=> $tourl
		);
		$this->load->view('showmsg/show_message', $msg_arr);
	}
	
	/**
	 * 如果非开发模式部分功能不能操作
	 */
	protected  function checkDev(){
		if ( !IS_DEVELOPMENT_MODEL ){
			return false;
		}
	}
	
	/**
	 * 获取网站站点配置数据
	 */
	public function getWebConfig(){
		$this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));//载入缓存,以文件形式存储
		$website = $this->cache->get('config_data') ;
		return $website;
	}
	
	/**
	 * 获取一级菜单
	 * @author Baip
	 */
	protected function getFirstMenu($controller=''){
		//获取点击当前主菜单的controller名称
		$controller = empty($controller) ? $this->uri->segment(1) : $controller;
		$where = array('pid'=>0,'hide'=>0);
		$this->load->model('Menu_model','menu');//载入Menu模型类
		//如果为开发模式
		if ( !IS_DEVELOPMENT_MODEL ){
			$where = array_merge($where, array('is_dev'=>0));
		}
		//获取主菜单
		$main_menus['main'] = $this->menu->getData(1,$where,'title,id,pid,url','sort DESC');
		//设置子节点
		$main_menus['child'] = array();
		
		//高亮主菜单
		$action_name = $this->uri->segment(2);//获取点击主导航的action_name的名称
		$gl_where = "url LIKE '%$controller/$action_name%'";//将得到的controller/actionname组合搜索条件
		$current = $this->menu->getFind(0,$gl_where,"id", "id ASC" ,1);
		
		if ( $current ){
			$nav = $this->menu->getPath($current['id']);//获取点击主导航及其子导航的数据
			$nav_first_title = $nav[0]['title'];
			
			foreach ($main_menus['main'] as $key => $item) {
				if (!is_array($item) || empty($item['title']) || empty($item['url']) ) {
					$this->show_message('error','控制器基类$main_menus属性元素配置有误');
				}
				//TODO 判断主菜单权限,最后加上
// 				if ( !IS_ROOT && !$this->checkRule($item['url'],AuthRuleModel::RULE_MAIN,null) ) {
// 					unset($main_menus['main'][$key]);
// 					continue;//继续循环
// 				}
				// 获取当前主菜单的子菜单项
				if($item['title'] == $nav_first_title){
					$main_menus['main'][$key]['class'] = 'active';//将点击选中的主菜单高亮
					$groups = $this->menu->getDistinct(array('pid' => $item['id']), 'group');
					if($groups){
						$groups = array_column($groups, 'group');
					}else{
						$groups =   array();
					}
					
					//获取二级分类的合法url
					$child_where = array('pid'=> $item['id'], 'hide'=>0);
					if( !IS_DEVELOPMENT_MODEL ){ // 是否开发者模式
						$child_where =  array_merge($where, array('is_dev'=>0));
					}
					$second_urls = $this->menu->getData(1, $where, 'id,url', 'sort ASC');
					//TODO 检测菜单权限　以后加上
					
					// 按照分组生成子菜单树
					foreach ($groups as $g) {
						$map = array('group'=>$g);
	// 					if(isset($to_check_urls)){
	// 						if(empty($to_check_urls)){
	// 							// 没有任何权限
	// 							continue;
	// 						}else{
	// 							$map['url'] = array('in', $to_check_urls);
	// 						}
	// 					}
						$map =  array('pid'=> $item['id'],'hide'=>0 );
						if( !IS_DEVELOPMENT_MODEL ){ // 是否开发者模式
							$map = array_merge($map, array('is_dev'=> 0) );
						}
						$menuList = $this->menu->getData(1, $map, 'id,pid,title,url,tip', 'sort DESC');
						$main_menus['child'][$g] = list_to_tree($menuList, 'id', 'pid', 'operater', $item['id']);
					}
				}else{
					$main_menus['main'][$key]['class'] = '';
				}	
				
			}	
		}
		$this->load->vars('main_menus', $main_menus);
	}
	
	/**
	 * 检测当前用户是否为管理员
	 * @param unknown_type $uid
	 * @author Baip
	 */
	public function is_administrator($uid = null){
		$uid = is_null($uid) ? is_login() : $uid;
		return $uid && (intval($uid) === C('USER_ADMINISTRATOR'));
	}
	
	/**
	 * 获取菜单的树形结构
	 * @author Baip
	 */
	public  function getCatgorytoTree($where="", $tree = true){
		$where = empty( $where ) ? array() : $where;
		$this->load->model('Catgory_model','catgory');//载入catgory模型类
		$catgory = $this->catgory->getData(1,$where,'title,id,pid');
		//检测是否有子栏目
		foreach ( $catgory as $key => $val ){
			$catgory[$key]['disabled'] = $this->catgory->getCount(array('pid'=>$val['id']),'*');
		}
		if ( $tree ){
			$this->load->library('Tree');//载入第三方树形结构类
			$catgory = $this->tree->toFormatTree($catgory);
			$catgory = array_merge(array(0=>array('id'=>0,'title_show'=>'请选择')), $catgory);
		}
		return $catgory;
	}
	
	/**
	 * 错误信息
	 */
	public function error(){
		return $this->error;
	}
	
	
}